<template>
  <div>
    <base-modal
      :show.sync="visible"
      :title="$t('common.base.statistics')"
      width="1000px"
      class="statistical-dialog"
      @closed="onClose('form')"
    >
      <div class="base-modal-content">
        <div class="statistical-search">
          <div class="search-left">
            <el-date-picker
              v-model="timeArrRange"
              type="daterange"
              range-separator="-"
              :start-placeholder="$t('common.base.startDate')"
              :end-placeholder="$t('common.base.endDate')"
              @change="onTimeChange"
              value-format="timestamp"
              :default-time="['00:00:00', '23:59:59']"
            >
            </el-date-picker>
            <el-input v-model="form.queryKey" :placeholder="placeholder"></el-input>
            <el-input v-model="form.operatorName" :placeholder="$t('customer.setting.statisticalDialog.pla1')"></el-input>
            <el-button type="primary" @click="onSearch">{{$t('common.base.search')}}</el-button>
          </div>
          <div class="search-right" v-if="isButtonDisplayed">       
            <a href="javascript:;" @click="exportData">{{$t('common.base.export')}}</a>
          </div>
        </div>
        <el-table
          ref="multipleTable"
          :data="tableData"
          style="width: 100%"
          class="page-table statistical-table"
          :highlight-current-row="false"
          :show-overflow-tooltip="true"
          border
          header-row-class-name="page-table-header" 
          stripe
          tooltip-effect="dark"
          v-loading="loading">
          <el-table-column :show-overflow-tooltip="true" prop="primaryId" :label="cardType==='customer'? $t('common.form.type.customerNo') :$t('common.form.type.productNo')" width="150">
            <template slot-scope="scope">
              <a @click="openCustomerView(scope.row.primaryId)">{{scope.row.primaryNo}}</a>
            </template>
          </el-table-column>
          <el-table-column :show-overflow-tooltip="true" prop="primaryName" :label="cardType==='customer'? $t('common.form.type.customerName') :$t('common.form.type.productName')" width="150">
            <template slot-scope="scope">
              {{cardType==='customer'?scope.row.customerName:scope.row.productName}}
            </template>
          </el-table-column>
          
          <el-table-column
            v-if="cardType==='product'"
            :label="$t('common.form.type.customerName')"
            prop="customerName"
          ></el-table-column>

          <el-table-column  
            v-for="(column, index) in columns" 
            :key="`${column.field}_${index}`"
            :prop="column.fieldName" 
            :label="column.displayName"
            :show-overflow-tooltip="true"
            :min-width="column.minWidth || '120px'">
            <template slot-scope="scope">
              <!-- start 自定义字段 -->
              <!-- start 多选 -->
              <template v-if="isMulti(column)">
                {{ (scope.row.taskCardInfos[column.fieldName] || []).join('，') }}
              </template>
              <!-- end 多选 -->
               <!-- start 备件 -->
              <template v-else-if="column.fieldName === 'part'">
                {{scope.row.taskCardInfos[column.fieldName]?scope.row.taskCardInfos[column.fieldName][0].name:''}}
              </template>
        <!-- end 备件 -->
              <template v-else>
                {{ $formatFormField(column, scope.row, 'taskCardInfos') }}
              </template>
              <!-- end 自定义字段 -->
              
            </template>
          </el-table-column>
          <el-table-column :label="$t('customer.setting.statisticalDialog.label1')" prop="userName" width="80px" show-overflow-tooltip></el-table-column>
          <el-table-column :label="$t('customer.setting.statisticalDialog.label2')" prop="operateTime" width="160px" show-overflow-tooltip>
            <template slot-scope="{row}">
              {{ row.operateTime | fmt_datetime }}
            </template>
          </el-table-column>
        </el-table>
        <div class="table-footer comment-list-table-footer">
          <div class="comment-list-table-footer-info task-flex task-ai">
            <i18n path="common.base.table.totalCount" tag="div">
              <span place="count" class="level-padding">{{totalElements || 0}}</span>
            </i18n>
            <!-- <div class="task-font14 task-c6 task-ml12">
              每页
              <el-select
                v-model="form.pageSize"
                placeholder="请选择"
                @change="handleSizeChange(form.pageSize)"
                class="table-footer-select"
              >
                <el-option :label="10" :value="10"></el-option>
                <el-option :label="20" :value="20"></el-option>
                <el-option :label="50" :value="50"></el-option>
              </el-select>
              条
            </div> -->
          </div>
          <el-pagination
            v-if="this.tableData"
            class="comment-list-table-footer-pagination"
            background
            :page-sizes="defaultTableData.defaultPageSizes"
            @current-change="jumpPage"
            @size-change="handleSizeChange"
            :page-size="form.pageSize"
            :current-page="form.pageNum"
            layout="prev, pager, next, sizes"
            :total="totalElements"
          >
          </el-pagination>
        </div>

      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="onClose">{{$t('common.base.cancel')}}</el-button>
        <el-button type="primary" @click="onClose" >{{$t('common.base.confirm')}}</el-button>
      </div>
    </base-modal>
    <div class="base-export-bridge" ref="bridge"></div>
  </div>
</template>
<script>
// api
import * as SettingCusProApi from '@src/api/SettingCusProApi';
// util
import fieldUtil from '../../task/taskAdditionalSetting/manage/components/cardField';
import http from "@src/util/http";
import Platform from "@src/platform";
import { checkButtonDisplayed } from '@src/util/dom';
import { openAccurateTab } from '@src/util/platform'
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'
import i18n from '@src/locales'
import { formatDate, useFormTimezone, nearDateBy, dayTimeEnd } from 'pub-bbx-utils';
import { defaultTableData } from '@src/util/table'
import { FieldTypeMappingEnum } from '@model/enum/FieldMappingEnum';
export default {
  name: 'statistical-dialog',
  props: {
    card:{
      type: Object,
      default: () => ({})
    },
    cardType:String
  },
  data() {
    return {
      defaultTableData,
      isButtonDisplayed: checkButtonDisplayed(),
      loading: true,
      visible: false,
      totalElements: 0,
      form: {
        cardType:'',
        cardId: '',
        startTime:'',
        endTime:'',
        pageNum: 1,
        pageSize: 10,
        queryKey: '',     // 编号/名称
        operatorName: ''
      },
      tableData:[],
      cardFieldsData:[],
      timeArrRange:[],
      action:'/excels/card/export'
    };
  },
  filters: {
    formatDate(val) {
      if (!val) return '';
      return formatDate(val, 'YYYY-MM-DD HH:mm')
    }
  },
  computed: {
    /** 
    * @description 表头设置
    */
    columns() {
      return fieldUtil.packProductFields(this.cardFieldsData)
    },
    placeholder(){
      return this.cardType==='customer'? i18n.t('customer.setting.statisticalDialog.pla2'): i18n.t('customer.setting.statisticalDialog.pla3')
    }
  },
  mounted() {
    this.form.cardType=this.cardType;
    this.timeRange();
  },
  methods: {
    /** 
    * @description 默认时间
    */
    timeRange() {
      this.timeArrRange = [+nearDateBy(1, 'month'), +dayTimeEnd()];
      this.form.startTime = this.timeArrRange[0];
      this.form.endTime = this.timeArrRange[1];
    },

    onTimeChange(e) {
      this.form.startTime = e?.[0]
      this.form.endTime = e?.[1]
    },

    /** 
    * @description 查看客户或产品详情
    */
    openCustomerView(id) {
      let fromId = window.frameElement.getAttribute('id');
      if(this.cardType==='customer'){
        // this.$platform.openTab({
        //   id: `customer_view_${id}`,
        //   title: '客户信息',
        //   close: true,
        //   url: `/customer/view/${id}?noHistory=1`,
        //   fromId
        // });
        openAccurateTab({
          type: PageRoutesTypeEnum.PageCustomerView,
          key: id,
          params: 'noHistory=1',
          fromId
        })
      }else if(this.cardType==='product'){
        // this.$platform.openTab({
        //   id: `product_view_${id}`,
        //   title: '产品详情',
        //   close: true,
        //   url: `customer/product/view/${id}?noHistory=1`,
        //   fromId
        // });
        openAccurateTab({
          type: PageRoutesTypeEnum.PageProductView,
          key: id,
          params: 'noHistory=1',
          fromId
        })
      }
    },

    /** 
    * @description 字段是否是多选类型
    */
    isMulti(field) {
      let { formType, setting = {}} = field;
      if (formType === 'selectMulti') return true;
      if (formType === 'select' && setting.isMulti) return true;
      return false;
    },
    /** 
    * @description 打开统计弹窗
    */
    openDialog() {
      this.visible = true;
      this.timeRange();

      if(this.card.id) {
        this.form.cardId = this.card.id;
        this.getCardFields()
        this.getCardCountReq();
      }
    },
    onClose(form) {
      this.visible = false;
      this.form = {
        cardType:this.cardType,
        cardId: '',
        startTime:'',
        endTime:'',
        pageNum: 1,
        pageSize: 10,
        queryKey: '',     // 编号/名称
        operatorName: ''   
      }
    },
    exportData(){
      if(this.tableData.length===0){
        return Platform.alert(this.$t('common.base.exportModal.atLeastOne'));
      }
      if(this.tableData.length>5000){
        return Platform.alert(this.$t('common.base.exportModal.oversizeTips', {size:5000}));
      }
      const form=this.form;
      const params={
        cardId:form.cardId,
        queryKey:form.queryKey,
        operatorName:form.operatorName,
        cardType:form.cardType,
        startTime:form.startTime,
        endTime:form.endTime,
        cardName:this.card.name,
        exportTotal:this.totalElements
      }
      return http
        .axios('post',this.action,params)
        .then(res=>{
          Platform.alert(res.message);
          if (res.status == 0) {
            window.parent.showExportList();
            window.parent.exportPopoverToggle(true);
          }
        })
        .catch(err => console.error(err));
    },
    /** 
    * @description 搜索
    */
    onSearch() {
      this.getCardCountReq()
    },

    /**
     * @description 页大小改变操作
     * @param {Number} pageSize 页大小
     */
    handleSizeChange(pageSize) {
      this.form.pageSize = pageSize;
      this.form.pageNum = 1;
      this.getCardCountReq();

    },
    /**
     * @description 页码跳转
     * @param {Number} pageNum 页码
     */
    jumpPage(pageNum) {
      this.form.pageNum = pageNum;
      this.getCardCountReq();
    },

    // 获取统计Fields列表
    getCardFields() {
      const params={
        cardType:this.cardType,
        id:this.card.id
      }
      SettingCusProApi.getCardFieldList(params).then(res=>{
        const { code, message, result = [] } = res;
        if( code == 0 ){
          this.cardFieldsData = result.filter(item=> item.formType !== FieldTypeMappingEnum.JsCodeBlock);;
        }else{
          this.$message.error(message);
        }
      }).catch(error=>({}))
    },

    // 获取统计列表
    getCardCountReq() {
      SettingCusProApi.getUsingList(this.form).then(res=>{
        this.loading = false;
        const { code, message, result } = res;
        if(code===0){
          this.totalElements = result.total;
          result.list.forEach(item=>{
            item.taskCardInfos = item.taskCardInfos ? JSON.parse(item.taskCardInfos) : {}
          })
          this.tableData = result.list;
        }else{
          this.$message.error(message);
        }
      }).catch(error=>({ }))

    }
  },
};
</script>
<style lang="scss">
.statistical-dialog {
  .base-modal-header {
    display: flex;
    justify-content: space-between;
    .el-dialog__title {
      font-size: 18px;
    }
    .el-tooltip {
      color: #999;
    }
  }
  .base-modal-body {
    padding: 20px;
    .base-modal-content{
      .statistical-search{
        display: flex;
        justify-content: space-between;
        .search-left{
          display: flex;
          justify-content: flex-start;
          .el-date-editor{
            margin-right: 12px;
            width: 256px !important;
          }
          .el-input{
            margin-right: 12px;
            width: 168px;
          }
        }
        .search-right{
          a{
            width: 58px;
            height: 32px;
           background: $color-primary-light-1;
            border-radius: 4px;
            border: 1px solid $color-primary-light-2;
            color: $color-primary-light-6;
            text-decoration: none;
            padding: 6px 10px;
          }
        }
      }
      .statistical-table{
        padding: 0;
        margin-top: 17px;  
        a{
          width: 100%;
          color: $color-primary-light-6;
          cursor: pointer;
          display: block;
          @include text-ellipsis();
        }
      }
      .table-footer{
        margin-top: 17px;
      }
      .el-table--border{
        border-bottom: 1px solid #ebeef5;
      }
    }
    

  }
}
</style>